<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">建筑业从业人员继续教育（管理端）</h3>
      </div>
      <div class="login-box">
        <div class="img-box">
          <img src="~@/assets/login_mini.png" alt="" />
          <div class="mask">
            <div class="text">
              <h1>继续教育</h1>
              <h2>全贵阳市建筑业从业人员都在用的考试系统</h2>
            </div>
          </div>
        </div>
        <div class="form-box">
          <div class="con-box">
            <h1 class="header">账号密码登录</h1>
            <el-form-item prop="username">
              <span class="svg-container">
                <svg-icon icon-class="user" />
              </span>
              <el-input
                v-model="loginForm.username"
                placeholder="账号"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
            </el-form-item>

            <el-tooltip
              v-model="capsTooltip"
              content="Caps lock is On"
              placement="right"
              manual
            >
              <el-form-item prop="password">
                <span class="svg-container">
                  <svg-icon icon-class="password" />
                </span>
                <el-input
                  :key="passwordType"
                  v-model="loginForm.password"
                  :type="passwordType"
                  placeholder="密码"
                  tabindex="2"
                  autocomplete="on"
                  @keyup.native="checkCapslock"
                  @blur="capsTooltip = false"
                  @keyup.enter.native="handleLogin"
                />
                <span class="show-pwd" @click="showPwd">
                  <svg-icon
                    :icon-class="
                      passwordType === 'password' ? 'eye' : 'eye-open'
                    "
                  />
                </span>
              </el-form-item>
            </el-tooltip>

            <!-- <el-form-item prop="code" class="code-input">
              <span class="svg-container">
                <svg-icon icon-class="user" />
              </span>
              <el-input
                v-model="loginForm.code"
                placeholder="验证码"
                name="username"
                type="text"
                tabindex="1"
                autocomplete="on"
              />
              <div class="append">
                <a href="#" @click.prevent="getCatcha" v-if="!state.smsSendBtn"
                  >获取验证码</a
                >
                <span v-else>{{ state.time + " s后重发" }}</span>
              </div>
            </el-form-item> -->
            <el-checkbox v-model="loginForm.rememberMe" style="float:right">
              记住账号
            </el-checkbox>
            <el-button
              :loading="loading"
              type="primary"
              class="submit-btn"
              @click.native.prevent="handleLogin"
              >登录</el-button
            >
          </div>
        </div>
      </div>
    </el-form>
    <div class="login-footer">
      <p>技术支持：贵阳市金阳建设数据服务有限公司</p>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import request from "@/utils/request";

export default {
  name: "Login",
  components: {},
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("请输入正确的账号"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("请输入密码，且不能少于6位"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "admin",
        password: "",
        rememberMe: true
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入登录账号" }
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword }
        ]
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      state: {
        time: 60,
        smsSendBtn: false
      }
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {},
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    // 获取验证码
    getCatcha() {
      const { state, loginForm } = this;
      this.$refs.loginForm.validateField(["username"], (err, values) => {
        if (!err) {
          state.smsSendBtn = true;
          const interval = setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60;
              state.smsSendBtn = false;
              clearInterval(interval);
            }
          }, 1000);
          request({
            url: "",
            method: "post",
            data: {
              phone: loginForm.username,
              captchaKey: ""
            }
          })
            .then(res => {
              if (res.code == 0) {
                this.$notify["success"]({
                  message: "提示",
                  description: "验证码获取成功",
                  duration: 8
                });
              } else {
                this.$notify["error"]({
                  message: res.msg
                });
              }
            })
            .catch(err => {
              clearInterval(interval);
              state.time = 60;
              state.smsSendBtn = false;
            });
        }
      });
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          let formData = {
            ...{ scope: "INSIDE", loginType: "INSIDE" },
            ...this.loginForm
          };
          this.$store
            .dispatch("user/login", formData)
            .then(() => {
              this.$router.push({
                path: this.redirect || "/exam/index",
                query: this.otherQuery
              });
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    }
  }
};
</script>

<style lang="scss">
$bg: #fff;
$light_gray: #fff;
$cursor: #000;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  /* background: url('~@/assets/login_bg.jpg') no-repeat;
  background-size: 100% 100%; */
  .el-input {
    display: inline-block;
    height: 42px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 0 5px 0 15px;
      color: #000;
      height: 42px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .code-input {
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
    .el-input {
      flex: 1;
    }
    .append {
      display: inline-block;
      margin-right: 10px;
      a {
        color: #42b983;
      }
      span {
        color: #999;
      }
    }
  }
  .el-form-item {
    border-radius: 5px;
    color: #000;
    border: 1px solid #ddd;
  }
}
</style>

<style lang="scss" scoped>
$bg: #f5f6f9;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  position: relative;

  .login-form {
    position: absolute;
    width: 920px;
    max-width: 100%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -55%);
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: #000;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: normal;
    }
  }

  // my-style
  .login-box {
    display: flex;
    align-items: stretch;
    flex-wrap: wrap;
    .img-box {
      width: 100%;
      flex: 1;
      height: 480px;
      position: relative;
      img {
        width: 100%;
        height: 100%;
      }
      .mask {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: rgba(0, 0, 0, 0.5);
        text-align: center;
        color: #fff;
        font-weight: 700;
        display: flex;
        align-items: center;
        justify-content: center;
        .text {
          h1 {
            font-size: 48px;
            margin-top: 0;
          }
          h2 {
            font-size: 18px;
            margin-top: 12px;
            margin-bottom: 20px;
          }
        }
      }
    }
    .form-box {
      flex: 1;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      .con-box {
        padding: 60px;
        width: 100%;
        .header {
          font-size: 16px;
          font-weight: normal;
          text-align: center;
          margin-bottom: 30px;
        }
        .submit-btn {
          width: 100%;
          margin-top: 60px;
          height: 42px;
        }
      }
    }
  }
  .login-footer {
    height: 40px;
    font-weight: 400;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    text-align: center;
    background-color: #000;
    color: #fff;
    p {
      line-height: 40px;
      font-size: 13px;
      margin: 0;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
